import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import { Search, Plus, Edit, Trash2, Save, RefreshCw, Filter, CalendarDays } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, Button, Input, Select, FormControlLabel } from '@mui/material';
import logger from '../../../utils/logger';

// 样式组件
const Container = styled.div`
  padding: 24px;
  background-color: #f8fafc;
  min-height: 100vh;
`;

const PageTitle = styled.h1`
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 24px;
`;

const ControlsBar = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
`;

const SearchBar = styled.div`
  display: flex;
  align-items: center;
  background: white;
  border-radius: 8px;
  padding: 8px 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  flex: 1;
`;

const SearchInput = styled.input`
  border: none;
  outline: none;
  flex: 1;
  margin-left: 8px;
  font-size: 14px;
  color: #334155;
`;

const ActionButton = styled.button`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  
  ${({ variant }) => {
    switch (variant) {
      case 'primary':
        return `
          background-color: #3b82f6;
          color: white;
          
          &:hover {
            background-color: #2563eb;
            transform: translateY(-1px);
          }
        `;
      case 'secondary':
        return `
          background-color: #f3f4f6;
          color: #374151;
          
          &:hover {
            background-color: #e5e7eb;
          }
        `;
      case 'danger':
        return `
          background-color: #ef4444;
          color: white;
          
          &:hover {
            background-color: #dc2626;
          }
        `;
      default:
        return '';
    }
  }}
`;

const TableContainer = styled.div`
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
`;

const Table = styled.table`
  width: 100%;
  border-collapse: collapse;
`;

const TableHeader = styled.th`
  background-color: #f9fafb;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
`;

const TableRow = styled.tr`
  &:hover {
    background-color: #f9fafb;
  }
`;

const TableCell = styled.td`
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
  color: #111827;
  font-size: 14px;
`;

const Pagination = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-top: 1px solid #e5e7eb;
  font-size: 14px;
`;

const StatusBadge = styled.span`
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  background-color: ${props => props.active ? '#dcfce7' : '#fee2e2'};
  color: ${props => props.active ? '#15803d' : '#b91c1c'};
`;

const BaziDatabase = () => {
  // 页面加载时记录访问日志
  useEffect(() => {
    logger.info('进入八字数据库管理页面');
  }, []);
  // 状态管理
  const [baziData, setBaziData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [currentItem, setCurrentItem] = useState(null);
  const [formData, setFormData] = useState({
    element: '',
    day: '',
    month: '',
    year: '',
    interpretation: '',
    compatibilityNotes: ''
  });
  
  // 模拟数据加载
  useEffect(() => {
    // 记录页面访问日志
    logger.info('进入八字数据库管理页面');
    
    const loadBaziData = async () => {
      try {
        // 在实际应用中，这里应该从API获取数据
        // const response = await axios.get('/api/bazi/database');
        // setBaziData(response.data);
        
        // 模拟数据
        const mockData = [
          {
            id: 1,
            element: '木',
            day: '甲子',
            month: '寅',
            year: '甲午',
            interpretation: '木生火，性格积极向上，创造力强',
            compatibilityNotes: '与火、土元素相生相克',
            createdAt: '2023-10-01',
            updatedAt: '2023-10-01'
          },
          {
            id: 2,
            element: '火',
            day: '丙午',
            month: '午',
            year: '乙未',
            interpretation: '火旺之人热情奔放，精力充沛',
            compatibilityNotes: '与土、金元素相生相克',
            createdAt: '2023-10-02',
            updatedAt: '2023-10-02'
          },
          {
            id: 3,
            element: '土',
            day: '戊辰',
            month: '辰',
            year: '丙申',
            interpretation: '土厚之人稳重踏实，责任感强',
            compatibilityNotes: '与金、水元素相生相克',
            createdAt: '2023-10-03',
            updatedAt: '2023-10-03'
          },
          {
            id: 4,
            element: '金',
            day: '庚申',
            month: '申',
            year: '丁酉',
            interpretation: '金旺之人坚韧不拔，逻辑性强',
            compatibilityNotes: '与水、木元素相生相克',
            createdAt: '2023-10-04',
            updatedAt: '2023-10-04'
          },
          {
            id: 5,
            element: '水',
            day: '壬子',
            month: '子',
            year: '戊戌',
            interpretation: '水旺之人聪明灵活，适应性强',
            compatibilityNotes: '与木、火元素相生相克',
            createdAt: '2023-10-05',
            updatedAt: '2023-10-05'
          }
        ];
        
        setBaziData(mockData);
        setFilteredData(mockData);
      } catch (error) {
        console.error('加载八字数据失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadBaziData();
  }, []);
  
  // 搜索过滤功能
  useEffect(() => {
    if (searchTerm === '') {
      setFilteredData(baziData);
    } else {
      const filtered = baziData.filter(item => 
        item.element.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.day.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.month.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.year.toLowerCase().includes(searchTerm.toLowerCase())
      );
      setFilteredData(filtered);
    }
  }, [searchTerm, baziData]);
  
  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 打开添加对话框
  const handleAddClick = () => {
    setFormData({
      element: '',
      day: '',
      month: '',
      year: '',
      interpretation: '',
      compatibilityNotes: ''
    });
    setIsAddDialogOpen(true);
  };
  
  // 打开编辑对话框
  const handleEditClick = (item) => {
    setCurrentItem(item);
    setFormData({
      element: item.element,
      day: item.day,
      month: item.month,
      year: item.year,
      interpretation: item.interpretation,
      compatibilityNotes: item.compatibilityNotes
    });
    setIsEditDialogOpen(true);
  };
  
  // 处理删除
  const handleDelete = (id) => {
    if (window.confirm('确定要删除这条记录吗？')) {
      // 记录删除日志
      logger.info(`删除八字数据库记录，ID: ${id}`);
      
      // 在实际应用中，这里应该调用API删除数据
      // axios.delete(`/api/bazi/database/${id}`);
      setBaziData(prev => prev.filter(item => item.id !== id));
    }
  };
  
  // 处理添加保存
  const handleAddSave = () => {
    // 记录添加日志
    logger.info(`添加八字数据库记录，元素: ${formData.element}`);
    
    // 在实际应用中，这里应该调用API添加数据
    // axios.post('/api/bazi/database', formData);
    const newItem = {
      id: baziData.length + 1,
      ...formData,
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0]
    };
    setBaziData(prev => [...prev, newItem]);
    setIsAddDialogOpen(false);
  };
  
  // 处理编辑保存
  const handleEditSave = () => {
    // 记录编辑日志
    logger.info(`编辑八字数据库记录，ID: ${currentItem.id}, 元素: ${formData.element}`);
    
    // 在实际应用中，这里应该调用API更新数据
    // axios.put(`/api/bazi/database/${currentItem.id}`, formData);
    setBaziData(prev => prev.map(item => 
      item.id === currentItem.id 
        ? { ...item, ...formData, updatedAt: new Date().toISOString().split('T')[0] }
        : item
    ));
    setIsEditDialogOpen(false);
  };
  
  // 渲染八字元素图标
  const renderElementIcon = (element) => {
    const colors = {
      '木': '#10b981',
      '火': '#f59e0b',
      '土': '#d97706',
      '金': '#6b7280',
      '水': '#3b82f6'
    };
    
    return (
      <span style={{ 
        display: 'inline-block', 
        width: '24px', 
        height: '24px', 
        borderRadius: '50%', 
        backgroundColor: colors[element] || '#6b7280',
        color: 'white',
        textAlign: 'center',
        lineHeight: '24px',
        fontSize: '12px',
        fontWeight: 'bold'
      }}>
        {element}
      </span>
    );
  };
  
  if (loading) {
    return (
      <Container>
        <PageTitle>八字数据库管理</PageTitle>
        <div style={{ textAlign: 'center', padding: '40px', color: '#64748b' }}>
          加载中...
        </div>
      </Container>
    );
  }
  
  return (
    <Container>
      <PageTitle>八字数据库管理</PageTitle>
      
      <ControlsBar>
        <SearchBar>
          <Search size={16} color="#64748b" />
          <SearchInput 
            placeholder="搜索元素、天干地支..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </SearchBar>
        
        <div style={{ display: 'flex', gap: '12px' }}>
          <ActionButton variant="secondary">
            <RefreshCw size={16} />
            刷新
          </ActionButton>
          <ActionButton variant="primary" onClick={handleAddClick}>
            <Plus size={16} />
            添加记录
          </ActionButton>
        </div>
      </ControlsBar>
      
      <TableContainer>
        <Table>
          <thead>
            <tr>
              <TableHeader>五行元素</TableHeader>
              <TableHeader>日柱</TableHeader>
              <TableHeader>月柱</TableHeader>
              <TableHeader>年柱</TableHeader>
              <TableHeader>解读内容</TableHeader>
              <TableHeader>兼容性说明</TableHeader>
              <TableHeader>创建时间</TableHeader>
              <TableHeader>操作</TableHeader>
            </tr>
          </thead>
          <tbody>
            {filteredData.map(item => (
              <TableRow key={item.id}>
                <TableCell>
                  {renderElementIcon(item.element)}
                  <span style={{ marginLeft: '8px' }}>{item.element}</span>
                </TableCell>
                <TableCell>{item.day}</TableCell>
                <TableCell>{item.month}</TableCell>
                <TableCell>{item.year}</TableCell>
                <TableCell>{item.interpretation}</TableCell>
                <TableCell>{item.compatibilityNotes}</TableCell>
                <TableCell>{item.createdAt}</TableCell>
                <TableCell>
                  <div style={{ display: 'flex', gap: '8px' }}>
                    <button 
                      onClick={() => handleEditClick(item)}
                      style={{
                        padding: '4px 8px',
                        border: 'none',
                        backgroundColor: '#3b82f6',
                        color: 'white',
                        borderRadius: '4px',
                        cursor: 'pointer'
                      }}
                    >
                      <Edit size={14} />
                    </button>
                    <button 
                      onClick={() => handleDelete(item.id)}
                      style={{
                        padding: '4px 8px',
                        border: 'none',
                        backgroundColor: '#ef4444',
                        color: 'white',
                        borderRadius: '4px',
                        cursor: 'pointer'
                      }}
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </tbody>
        </Table>
        
        <Pagination>
          <span>显示 {filteredData.length} 条记录</span>
          <div>
            {/* 分页控件可以在这里添加 */}
            页码: 1
          </div>
        </Pagination>
      </TableContainer>
      
      {/* 添加对话框 */}
      <Dialog open={isAddDialogOpen} onClose={() => setIsAddDialogOpen(false)}>
        <DialogTitle>添加八字记录</DialogTitle>
        <DialogContent>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>五行元素</label>
              <select
                name="element"
                value={formData.element}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
              >
                <option value="">请选择</option>
                <option value="木">木</option>
                <option value="火">火</option>
                <option value="土">土</option>
                <option value="金">金</option>
                <option value="水">水</option>
              </select>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>日柱</label>
              <input
                type="text"
                name="day"
                value={formData.day}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                placeholder="如：甲子"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>月柱</label>
              <input
                type="text"
                name="month"
                value={formData.month}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                placeholder="如：寅"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>年柱</label>
              <input
                type="text"
                name="year"
                value={formData.year}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                placeholder="如：甲午"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>解读内容</label>
              <textarea
                name="interpretation"
                value={formData.interpretation}
                onChange={handleInputChange}
                rows={3}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px',
                  resize: 'vertical'
                }}
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>兼容性说明</label>
              <textarea
                name="compatibilityNotes"
                value={formData.compatibilityNotes}
                onChange={handleInputChange}
                rows={2}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px',
                  resize: 'vertical'
                }}
              />
            </div>
          </div>
        </DialogContent>
        <div style={{ padding: '16px', display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
          <Button onClick={() => setIsAddDialogOpen(false)}>取消</Button>
          <Button onClick={handleAddSave} variant="contained">保存</Button>
        </div>
      </Dialog>
      
      {/* 编辑对话框 */}
      <Dialog open={isEditDialogOpen} onClose={() => setIsEditDialogOpen(false)}>
        <DialogTitle>编辑八字记录</DialogTitle>
        <DialogContent>
          {/* 编辑表单内容，与添加表单类似 */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>五行元素</label>
              <select
                name="element"
                value={formData.element}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
              >
                <option value="">请选择</option>
                <option value="木">木</option>
                <option value="火">火</option>
                <option value="土">土</option>
                <option value="金">金</option>
                <option value="水">水</option>
              </select>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>日柱</label>
              <input
                type="text"
                name="day"
                value={formData.day}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                placeholder="如：甲子"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>月柱</label>
              <input
                type="text"
                name="month"
                value={formData.month}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                placeholder="如：寅"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>年柱</label>
              <input
                type="text"
                name="year"
                value={formData.year}
                onChange={handleInputChange}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                placeholder="如：甲午"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>解读内容</label>
              <textarea
                name="interpretation"
                value={formData.interpretation}
                onChange={handleInputChange}
                rows={3}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px',
                  resize: 'vertical'
                }}
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontSize: '14px', fontWeight: '500' }}>兼容性说明</label>
              <textarea
                name="compatibilityNotes"
                value={formData.compatibilityNotes}
                onChange={handleInputChange}
                rows={2}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '14px',
                  resize: 'vertical'
                }}
              />
            </div>
          </div>
        </DialogContent>
        <div style={{ padding: '16px', display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
          <Button onClick={() => setIsEditDialogOpen(false)}>取消</Button>
          <Button onClick={handleEditSave} variant="contained">保存</Button>
        </div>
      </Dialog>
    </Container>
  );
};

export default BaziDatabase;